//
//  OAuthViewController.swift
//  WeiBo
//
//  Created by wukeng on 16/8/27.
//  Copyright © 2016年 wukeng. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {
    @IBOutlet weak var webView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavi()
        
        //加载网页
       loadPage()
    }
}

// MARK: - 设置UI界面
extension OAuthViewController{
    private func setupNavi(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: #selector(OAuthViewController.goBackClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: #selector(OAuthViewController.fillItemClick))
        title = "登录页面"
    }
    
    private func loadPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_Key)&redirect_uri=\(redirect_uri)"
        //创建url
        guard let url = NSURL(string: urlString) else{
            return
        }
        //创建request
        let urlRequest = NSURLRequest(URL: url)
        //加载request对象
        webView.loadRequest(urlRequest)
        
    }
}
// MARK: - 事件监听
extension OAuthViewController{
    @objc private func goBackClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func fillItemClick(){
        print("fillItemClick")
        let jsCode = "document.getElementById('userId').value='13771079670';document.getElementById('passwd').value='wkmt520124'"
        
        //执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
}

// MARK: - webView的代理
extension OAuthViewController : UIWebViewDelegate{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    //当准备加载某网页时，会执行该方法。
    //返回值:true -> 继续加载该页面， false -> 不会加载该页面
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let url = request.URL else{
            return true
        }
        
        let urlString = url.absoluteString
        
        guard urlString.containsString("code=") else{
            return true
        }
        
        let code = urlString.componentsSeparatedByString("code=").last
        
        
        loadAccessToken(code!)
        
        return false
    }
}

// MARK: - 请求数据
extension OAuthViewController{
    private func loadAccessToken(code : String){
        NetworkTools.shareInstance.loadAccess_Token(code) { (result, error) in
            if error != nil{
                print(error)
                return
            }
            else{
                guard let accountDict = result else{
                    return
                }
                let account = UserAccount(dict: accountDict)
                //请求用户信息
                self.loadUserInfo(account)
            }
        }
    }
    //请求用户信息
    private func loadUserInfo(account : UserAccount){
        guard let access_token = account.access_token else{
            return
        }
        guard let uid = account.uid else{
            return
        }
        NetworkTools.shareInstance.loadUserinfo(access_token, uid: uid) { (result, error) in
            guard let userInfoDict = result else{
                return
            }
            account.screen_name = userInfoDict["screen_name"] as? String
            account.avatar_large = userInfoDict["avatar_large"] as? String
            //将account存储起来
            //2.保存对象
            NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.single.accountPath)
            //把account对象设置到单例对象中（因为创建单例的时候，account为nil。）
            UserAccountViewModel.single.account = account
            //5.退出当前控制器
            self.dismissViewControllerAnimated(false, completion: {
                UIApplication.sharedApplication().keyWindow?.rootViewController = WelcomeViewController()
            })
        }
    }
}




